#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

//统计大小
off_t mywcsize(const char *filename);
//统计行数
int mywcrow(const char *filename);
//统计单词
int mywcword(const char *filename);

int main(int argc, const char* argv[])
{
    //判断参数个数
    if(argc == 2)
    {
        int row = 0;
        row = mywcrow(argv[1]);
        off_t size = 0;
        size = mywcsize(argv[1]);
         int word = 0;
        word = mywcword(argv[1]);
        printf("%d  %d  %ld  %s\n", row, word, size, argv[1]);
    }
    else if(argc == 3)
    {
        if(!strcmp(argv[1],"-l")) // 行数
        {
            int row = 0;
            row = mywcrow(argv[2]);
            printf("%d  %s\n", row, argv[2]);
        }
        else if(!strcmp(argv[1], "-c"))  //大小
        {
            off_t size = 0;
            size = mywcsize(argv[2]);
            printf("%ld  %s\n", size, argv[2]);
        }
        else if(!strcmp(argv[1], "-w"))  //单词数
        {
            int word = 0;
            word = mywcword(argv[2]);
            printf("%d  %s\n", word, argv[2]);
        }
    }

    return 0;
    
}

off_t mywcsize(const char *filename)
{
    int pf;
    off_t len = 0;

    pf = open(filename, O_RDONLY);
    if(pf == -1)
    {
        printf("文件打开失败！");
        return 0;
    }

    len = lseek(pf, 0, SEEK_END);  //到文件末尾，返回文件大小

    close(pf);

    return len;
}

int mywcrow(const char *filename)
{
    int pf;
    int row = 1; 
    int len = 0;
    char str[10] = {0};

    pf = open(filename, O_RDONLY);
    if(pf == -1)
    {
        printf("文件打开失败！");
        return 0;
    }

    while((len = read(pf, str, sizeof(str))) != 0)
    {
        if(len == -1)
        {
            printf("读取数据错误！\n");
            break;
        }
        for(int i = 0; i < len; i++)
        {
            if(str[i] == '\n')
            {
                row++;
            }
        }
    }

    close(pf);

    return row;
}

int mywcword(const char *filename)
{
    int pf;
    int wordnum = 0;
    int len = 0;
    char str[10] = {0};

    pf = open(filename, O_RDONLY);
    if(pf == -1)
    {
        printf("文件打开失败！");
        return 0;
    }

    while((len = read(pf, str, sizeof(str))) != 0)
    {
        if(len == -1)
        {
            printf("读取数据错误！\n");
            break;
        }
        for(int i = 0; i < len; i++)
        {
            if(isspace(str[i]))
            {
                if(isspace(str[i + 1]))
                {
                    wordnum++;
                }
            }
        }
    }

    close(pf);

    return wordnum;
}